import { defineStore } from 'pinia';
import app from './app';
import FittingRoomApi from '../api/fittingRoom';
import sheep from '@/sheep';

const _tabsMap = [undefined, 'topCloth', 'bottomCloth', 'dress', 'suit', 'hair', 'hair'];

const isOpened = window.location.href.includes('open=1');
console.log('isOpened: ', isOpened);

export const pattern = [
  { value: 'body', label: '胸' },
  { value: 'waist', label: '腰' },
  { value: 'thigh', label: '跨' },
  { value: 'thigh1', label: '大腿' },
  // { value: 'thigh1', label: '大腿上部1/3' },
  // { value: 'thigh2', label: '大腿中部' },
  { value: 'knee', label: '膝盖' },
  { value: 'leg', label: '小腿' },
  // { value: 'leg1', label: '小腿上部1/3' },
  { value: 'foot', label: '脚踝' },
  { value: 'mopping', label: '拖地' },
];

const fittingRoom = defineStore({
  id: 'fittingRoom',
  state: () => ({
    swiperCurrentIndex: 0,
    visable: false, // 上传模特, 选模特的
    modelList: [], // 模特列表
    currentModel: {},
    type: false, // true: 我的衣橱, false: 衣服库
    tab: isOpened ? 6: 0, // 对应下面tabs的序号
    tabs: ['全部', '上衣', '下装', '连衣裙', '外套', '套装', '发型'],
    tabsMap: _tabsMap,
    disableTabs: [6], // 不允许上传图的tab索引
    clothes: [], // 接口返回的衣服数据
    currentClothes: [], // 当前选的衣服
    selectClothesType: 1, // 选中的衣服类型, 默认选中上衣
    selectPattern: pattern[0].value, // 上传或者编辑衣服的时候的长短
    sex: 'female',
    testResults: [], // 当前模特的试穿结果列表
  }),
  getters: {
    // 能上传图片的场景
    canUpload(state) {
      // 除了发型其他都能上传
      return this.type && !this.disableTabs.includes(this.tab);
    },
    // 有没有试穿结果没生成的
    generatingLoading(state) {
      return this.testResults.some((item) => !item.tryOnResultUrl);
    },
  },
  actions: {
    // 获取衣服分类
    async getCategory(templateId = null) {
      const httpResponse = await FittingRoomApi.getCategory();
      let result = httpResponse.data[0]?.children;
      this.tabs = ['全部', ...result?.map((item) => item.name), '发型'];
      this.tabsMap = [undefined, ...result?.map((item) => item.id), 'hair'];
      this.selectClothesType = result[0].id;
    },

    async getTestResults(modelId = '') {
      const httpResponse = await FittingRoomApi.getTestResults({
        modelId,
        pageNo: '1',
        pageSize: '30',
      });
      const result = httpResponse.data?.list ?? [];
      // result.reverse();
      // 将模特放到最后一张
      result.push({
        id: 100000,
        modelId: modelId,
        modelImageUrl:
          'https://tupian05.oss-cn-beijing.aliyuncs.com/digital_cloth/1758853865858.png',
        clothingImageUrl:
          'https://tupian05.oss-cn-beijing.aliyuncs.com/digital_cloth/1758795488865.jpg',
        tryOnResultUrl: this.currentModel.fileUrl,
        // "userId": 284,
        // "createTime": 1758857790000
      });
      this.testResults = result;
      return result;
    },

    // 获取衣服类型数据查询
    async getCloths(templateId = null) {
      const httpResponse = await FittingRoomApi.getClothList({
        sex: 'female',
        isPerson: this.type ? 'yes' : 'no',
        clothType: this.tabsMap[this.tab],
      });
      // 如果我的衣橱就往前加个空数组
      this.clothes = this.canUpload
        ? [{}, ...(httpResponse.result || [])]
        : httpResponse.result || [];
    },
    // 获取模特数据查询
    async getModelList(modelId = undefined) {
      const httpResponse = await FittingRoomApi.getModelList({
        sex: this.sex,
      });
      let modelList = httpResponse.result || [];
      this.modelList = modelList;
      if (modelId) {
        this.currentModel = modelList.find((item) => item.id === modelId);
        // this.getTestResults(modelId);
        return;
      }
      this.currentModel = modelList?.[0] ?? {};
      this.getTestResults(modelList?.[0]?.id);
    },
    // 试穿
    async tryOn() {
      if (!this.currentModel?.id) {
        sheep.$helper.toast('请选择模特');
        return;
      }
      if (!this.currentClothes?.[0]?.fileUrl) {
        sheep.$helper.toast('请选择衣服');
        return;
      }

      const fittingRoomStore = sheep.$store('fittingRoom');
      // 那改成 clothUrl 和 kuziUrl 吧，当 kuziUrl 有值时，再传个  suit: true
      const httpResponse =
        this.tab === 6
          ? await FittingRoomApi.hairstyleTryOnApi({
              modelId: this.currentModel.id,
              files: this.currentModel.fileUrl,
              isHr: true,
              hairIds: this.currentClothes[0]?.clothId,
              sex: 'female',
            })
          : await FittingRoomApi.tryOnApi({
              modelId: this.currentModel.id,
              modelImageUrl: this.currentModel.fileUrl,
              clothUrl: this.currentClothes[0]?.fileUrl,
              kuziUrl: this.currentClothes?.[1]?.fileUrl
                ? this.currentClothes[1]?.fileUrl
                : undefined,
              suit: this.currentClothes?.[1]?.fileUrl ? true : undefined,
              cloth_len: pattern.find((i) => i.value === this.currentClothes[0]?.len)?.label,
              len: pattern.find((i) => i.value === this.currentClothes[0]?.len)?.label,
            });
      if (httpResponse.code !== 0) {
        sheep.$helper.toast(httpResponse.msg);
        return;
      }
      this.getTestResults(this.currentModel.id);
      this.swiperCurrentIndex = 0;
    },
    // 切换模特
    switchModels(item) {
      if (item.id === this.currentModel.id) {
        return;
      }
      console.log('🚀 ~ switchModels 🐶106 ~ item: ', item);
      this.currentModel = item;
      this.setVisable();
      this.getTestResults(item.id);
    },
    async uploadAndEditCloth(data = {}) {
      await FittingRoomApi.uploadAndEditCloth({
        clothType: this.selectClothesType,
        isSync: 'yes',
        sex: this.sex,
        len: this.selectPattern,
        isPerson: 'yes', // /cloth/uploadCloth   h5端多传一个参数isPerson=yes
        ...data,
      });
    },
    setVisable(visable) {
      console.log('🚀 ~ setVisable ?1207 ~ visable: ', visable);
      this.visable = visable ?? !this.visable;
    },
    // 我的衣服库和衣橱的切换
    changeType(visable) {
      console.log('🚀 ~ setVisable ?1128 ~ visable: ', visable);
      this.type = visable ?? !this.type;
      this.getCloths();
    },

    changeTheSelected(data) {
      console.log('🚀 ~ changeTheSelected ?1310 ~ data: ', data);
      this.selectPattern = data.selectPattern;
      this.selectClothesType = data.selectClothesType;
    },

    changeTab(index) {
      console.log('切换tab');
      this.tab = index;
      this.getCloths();
    },
    // 点击衣服
    changeClothes(data) {
      console.log('changeClothes: 2222222222222222222222222222222',);
      const shangyi = '95'; // 上衣
      const xiazhuang = '96'; // 上衣
      console.log('ppppppppppppppppp ~ changeClothes ~ data: xxxxx', data.clothType);
      if (this.currentClothes?.length === 0) {
        this.currentClothes = [data];
        return;
      }
      // 如果选了一个, 第一个是上衣
      if (this.currentClothes?.length === 1 && this.currentClothes[0].clothType === shangyi) {
        if (data.clothType === shangyi) {
          this.currentClothes = [data];
          return;
        }
        if (data.clothType === xiazhuang) {
          this.currentClothes = [...this.currentClothes, data];
          return;
        }
        if (data.clothType !== xiazhuang && data.clothType !== shangyi) {
          this.currentClothes = [data];
          return;
        }
      }
      if (this.currentClothes?.length === 1 && this.currentClothes[0].clothType === xiazhuang) {
        if (data.clothType === shangyi) {
          this.currentClothes = [data, this.currentClothes[0]];
          return;
        }
        if (data.clothType === xiazhuang) {
          this.currentClothes = [data];
          return;
        }
        if (data.clothType !== xiazhuang && data.clothType !== shangyi) {
          this.currentClothes = [data];
          return;
        }
      }
      if (this.currentClothes?.length === 2) {
        if (data.clothType === shangyi) {
          this.currentClothes = [data, this.currentClothes[1]];
          return;
        }
        if (data.clothType === xiazhuang) {
          this.currentClothes = [this.currentClothes[0], data];
          return;
        }
        if (data.clothType !== xiazhuang && data.clothType !== shangyi) {
          this.currentClothes = [data];
          return;
        }
      }
      this.currentClothes = [data];

      console.log('切换衣服');
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'fittingRoom-store',
      },
    ],
  },
});

export default fittingRoom;
